package Socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket ss;

    private ExecutorService pool;

    public Server()
    {
        try {
            System.out.println("正在启动服务端");
            ss=new ServerSocket(8088);
            pool = Executors.newFixedThreadPool(20);
            System.out.println("启动服务端成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start()
    {
        try {
            while(true) {
                System.out.println("等待客户端链接");
                Socket socket = ss.accept();
                System.out.println("一个客户端链接成功");

                ClientHandler clienthandler = new ClientHandler(socket);
//                Thread thread = new Thread(clienthandler);
//                thread.start();
                pool.execute(clienthandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
    private class ClientHandler implements Runnable
    {
        private Socket socket;

        public ClientHandler(Socket socket)
        {
            this.socket=socket;
        }
        @Override
        public void run() {
            try {
                InputStream is=socket.getInputStream();

                int len;
                while((len=is.read())!=-1) {
                    byte[] bytes = new byte[len];
                    is.read(bytes);

                    String message = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("客户端说：" + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
